package com.beerandjesus.sportofkings.handicapper.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Date: Jul 7, 2012
 * Time: 8:05:09 PM
 */
public class AbstractDAOImpl implements AbstractDAO {

    private ConnectionManager connectionManager;

    protected void executeStatementIgnoringException(Connection connection, String statement) {
        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement(statement);
            stmt.execute();
        } catch (SQLException e) {
            // ignore
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                // ignore
            }
        }
    }

    protected void executeStatement(Connection connection, String statement) throws DAOException {
        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement(statement);
            stmt.execute();
        } catch (SQLException e) {
            throw new DAOException("Error creating table", e);
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                // ignore
            }
        }
    }

    protected int getRowCount(Connection connection, String table) throws DAOException {
        PreparedStatement smt;
        try {
            smt = connection.prepareStatement("select count(*) from " + table);
            ResultSet rs = smt.executeQuery();
            if (!rs.next()) {
                return 0;
            }
            return rs.getInt(1);
        } catch (SQLException e) {
            throw new DAOException("Error getting row count", e);
        }
    }

    public ConnectionManager getConnectionManager() {
        return connectionManager;
    }

    public void setConnectionManager(ConnectionManager connectionManager) {
        this.connectionManager = connectionManager;
    }
}
